<script lang="ts" setup name="grantDialog">
import { ref, watch, reactive } from "vue";
import { ElForm, ElMessage } from "element-plus";
// interface List {
//   content: string;
//   desc: string;
//   id: number;
//   name: string;
//   sign: string;
//   templateCode: string;
//   type: number;
//   variable: string;
//   variableObject: string[];
// }
interface Props {
  isVisible: boolean;
  // list: List[] | [];
  title: string;
  userIds?: number[];
}
const props = ref<Props>({
  isVisible: false,
  // list: [],
  title: ""
});
// 父组件传递数据
const templateList = ref<string[]>([]); // 模版数组
const acceptParams = (params: { [key: string]: any }) => {
  props.value.isVisible = true;
  props.value.title = params.title;
  // props.value.list = params.list && JSON.parse(JSON.stringify(params.list));
  // formData.value.templateCode = params.list && params.list[0].templateCode;
  // formData.value.content = params.list && `${params.list[0].content}`;
  // params.list &&
  //   params.list[0].variableObject.forEach((key: any) => {
  //     formData.value.variables[key] = "";
  //   });
  formData.value.userIds = params.userIds && JSON.parse(JSON.stringify(params.userIds));
  // templateList.value = params.list && params.list[0].variableObject;
};

// 传给后台数据
export interface FormData {
  sendTime: string;
  templateCode: string;
  content: string;
  type: number;
  variables: any;
  userIds: number[];
}
const fromRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref<FormData>({
  templateCode: "",
  content: "",
  variables: {}, // 模版内容对象
  type: 1, // 1.立即发送 2 定时发送
  sendTime: "", // 发送时间
  userIds: []
});

const rules = reactive({
  sendTime: [
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (formData.value.type === 2 && !value) {
          callback(new Error("请选择发放日期"));
        }
        callback();
      }
    }
  ],
  content: [{ required: true, message: "请输入模版内容" }]
});

// 选择模版后触发
// const onchangeTemplate = (e: string) => {
//   formData.value.variables = {};
//   const index = props.value.list.findIndex(v => v.templateCode === e);
//   formData.value.templateCode = e;
//   formData.value.content = props.value.list[index].content;
//   templateList.value = props.value.list[index].variableObject;
//   props.value.list[index].variableObject.forEach(key => {
//     formData.value.variables[key] = "";
//   });
// };

const isFlag = ref(false);
// 输入内容替换
// const showTemplate = () => {
//   try {
//     templateList.value.forEach(v => {
//       if (formData.value.variables[v] === "") throw new Error("");
//       let regex = new RegExp("\\${" + v + "}", "g");
//       formData.value.content = formData.value.content.replace(regex, formData.value.variables[v]);
//     });
//     isFlag.value = true;
//   } catch (e) {
//     ElMessage({ message: "请输入输入框内容", type: "warning" });
//   }
// };
interface Emits {
  (name: "confirm", value: FormData): void;
}
const emits = defineEmits<Emits>();

const onConfirm = async () => {
  await fromRef.value?.validate();
  // if (!isFlag.value) return ElMessage({ message: "请先查看模版最终效果", type: "warning" });
  emits("confirm", formData.value);
};

watch(
  () => props.value.isVisible,
  newV => {
    isFlag.value = false;
    if (!newV) {
      formData.value = {
        templateCode: "",
        content: "",
        variables: {}, // 模版内容对象
        type: 1, // 1.立即发送 2 定时发送
        sendTime: "", // 发送时间
        userIds: []
      };
    }
  }
);
// 关闭或打开编辑框
const changeVisible = (e: boolean) => {
  props.value.isVisible = e;
};

const onClose = () => {
  props.value.isVisible = false;
};

defineExpose({
  acceptParams,
  changeVisible
});
</script>

<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      style="padding: 20px"
      v-model="props.isVisible"
      :title="props.title"
      width="600"
      :before-close="onClose"
    >
      <el-form
        ref="fromRef"
        :rules="rules"
        style="box-sizing: border-box; padding: 0 60px 0 40px"
        :model="formData"
        label-width="100"
        label-position="left"
      >
        <!-- <el-form-item label="发送类型:">
          <div>短信信息</div>
        </el-form-item> -->
        <el-form-item prop="type" label="发送类型:">
          <el-radio-group v-model="formData.type">
            <el-radio :value="1">立即发送</el-radio>
            <el-radio :value="2">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.type === 2" prop="sendTime" label="发送时间:">
          <el-date-picker
            v-model="formData.sendTime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            type="datetime"
            placeholder="请选择时间"
          />
        </el-form-item>

        <el-form-item label="模版内容:" prop="content">
          <el-input :rows="4" v-model="formData.content" type="textarea"></el-input>
        </el-form-item>

        <el-form-item>
          <div style="width: 100%; font-size: 12px; text-align: right">合计：{{ formData.userIds.length }}个会员</div>
          <div style="width: 100%; font-size: 12px; color: #fe2214; text-align: right">提示：每70个字符算为一条短信。</div>
        </el-form-item>

        <!-- <el-form-item label="发送模版:">
          <el-select @change="onchangeTemplate" v-model="formData.templateCode">
            <el-option v-for="item in props.list" :label="item.name" :key="item.templateCode" :value="item.templateCode" />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item :label="item + ':'" v-for="item in templateList" :key="item">
            @change="onChange(item, $event, formData.variables[item])" 
          <el-input v-model="formData.variables[item]"></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="模版内容:">
          <el-input :rows="4" disabled v-model="formData.content" type="textarea"></el-input>
        </el-form-item> -->
        <!-- 
        <el-form-item>
          <div style="width: 100%; font-size: 12px; color: #7f7f7f; text-align: right">
            变量限制：不支持QQ号、微信号、网址信息；1~35位字符
          </div>
        </el-form-item> -->

        <!-- <el-form-item label="">
          <el-button @click="showTemplate" type="primary" size="small">显示模版最终效果</el-button>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="onConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.el-message {
  z-index: 9999 !important; /* 设置一个足够高的 z-index 值 */
}
</style>
